package com.glorysoft.wangnianxinpda.activity;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.adapter.RecyclerViewAdapter;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.entity.BasShortcutIconInfoEntity;
import com.glorysoft.wangnianxinpda.entity.PDALoginReturnEntity;
import com.glorysoft.wangnianxinpda.recyevent.OnRecyclerItemClickListener;
import com.glorysoft.wangnianxinpda.utils.FileUtils;
import com.glorysoft.wangnianxinpda.utils.GsonUtils;
import com.glorysoft.wangnianxinpda.utils.ResultSet;
import com.glorysoft.wangnianxinpda.utils.ToastUtil;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends BaseActivity {
    private final String TAG = HomeActivity.class.getSimpleName();
    private Context mContext;

    private ViewPager mViewPager;
    private View viewFunction; //功能管理

    private TextView tvTtitle;
    private ImageView ivBack;
    private ImageView ivExit;
    private RecyclerView recyclerViewMfg; //显示-快捷图标(MFG)
    private RecyclerView recyclerViewPe; //显示-快捷图标(PE)
    private LinearLayout llMfg;
    private LinearLayout llPe;
    private View vMfg;
    private View vPe;
    private LinearLayout llMain;

    private List<View> viewList = new ArrayList<View>(); //滑动UI
    private FunPagerAdapter mAdapter; //首页菜单-适配器

    //快捷方式数据
    private List<BasShortcutIconInfoEntity> mBasShortcutIconInfoMfgList = null;
    private List<BasShortcutIconInfoEntity> mBasShortcutIconInfoPeList = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListenerView();//控件事件
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_home;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
        mContext = this;

        mViewPager = findViewById(R.id.view_pager);
        llMain = findViewById(R.id.llMain);
        tvTtitle = findViewById(R.id.tvTtitle);
        ivBack = findViewById(R.id.ivBack);
        ivExit = findViewById(R.id.ivExit);

        ivBack.setOnClickListener(v ->{finish();});
        ivExit.setOnClickListener(v ->{FreeApi_ActivityManager.getActivityManager().AppExit(mContext);});
        tvTtitle.setOnClickListener(v ->{FreeApi_Utils.skipWithExtraIntent("header", mContext, MineInfoActivity.class);});
        String work_no = Constant.loginEntity.getWORK_NO();
        String name = Constant.loginEntity.getNAME();
        tvTtitle.setText(work_no + " - " + name);
//        tvTtitle.setText("OP1111" + " - " + "张三");
        //功能管理
        viewFunction = View.inflate(mContext, R.layout.fragment_main_bottom_function, null);

        //viewList添加数据
        viewList.add(viewFunction);
    }

    @Override
    protected void initData() {

        //首页底部菜单-适配器
        mAdapter = new FunPagerAdapter(viewList);
        mViewPager.setAdapter(mAdapter);

        //修改RadioButton drawableTop图片大小 --图片放在drawable-xxhdpi目录下，此处则不用修改
//        modifyRadioButton();

        //初始化数据-MFG
        initFragmentMfgFunctionView();
        //初始化数据-PE
        initFragmentPeFunctionView();
        //初始化数据-我的的信息
//        initFragmentMmainMineInfoView();

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    //region 首页底部菜单页面滑动-初始化数据

    //初始化数据-MFG
    private void initFragmentMfgFunctionView() {
        recyclerViewMfg = viewFunction.findViewById(R.id.rvMfg);  //显示-快捷图标(MFG)
        vMfg = viewFunction.findViewById(R.id.vMfg);  //页签
        llMfg = viewFunction.findViewById(R.id.llMfg);
        llMfg.setOnClickListener(v -> {
            if (recyclerViewMfg.getVisibility() == View.GONE){
                recyclerViewMfg.setVisibility(View.VISIBLE);
                vMfg.setBackground(getResources().getDrawable(R.drawable.shape_view_red));
            }else {
                recyclerViewMfg.setVisibility(View.GONE);
                vMfg.setBackground(getResources().getDrawable(R.drawable.shape_view_white));
            }
        });

        if (mBasShortcutIconInfoMfgList == null) {
            mBasShortcutIconInfoMfgList = new ArrayList<>();
        }

        //region 获取mfg本地Json数据(快捷图标)

        try {
            //获取本地Json数据(快捷图标)
            ResultSet resultSetData = FileUtils.readJson(mContext, "mfg.txt");
            if (resultSetData.status == 0) {
                String sShortcutJson = resultSetData.getData().toString();
                if (!TextUtils.isEmpty(sShortcutJson)) {
                    //解析JSON
                    JSONArray jsonArray = new JSONArray(sShortcutJson);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String sData = jsonObject.getString("data");
                    JSONArray jsonArrayData = new JSONArray(sData);
                    JSONObject jsonObjectData = jsonArrayData.getJSONObject(0);
                    PDALoginReturnEntity mPDALoginReturnEntity = GsonUtils.getObject(jsonObjectData.toString(), PDALoginReturnEntity.class);
                    mBasShortcutIconInfoMfgList.addAll(mPDALoginReturnEntity.getTabIndexGridEntityList());

                } else {
                    ToastUtil.showShortToast(mContext, resultSetData.msg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

//endregion

//region 初始化数据

        if (mBasShortcutIconInfoMfgList.size() >= 1) {

            //设置网格布局管理器
            recyclerViewMfg.setLayoutManager(new GridLayoutManager(mContext, 3));
            // 设置adapter
            //快捷方式适配器(mfg)
            RecyclerViewAdapter mRecyclerViewMfgAdapter = new RecyclerViewAdapter(mContext, R.layout.item_main_operate, mBasShortcutIconInfoMfgList);

            //分割线
            //recyclerViewMfg.addItemDecoration(new DividerGridItemDecoration(this));
            recyclerViewMfg.setHasFixedSize(true);

            // recyclerViewMfg  调用自己的addOnItemTouchListener方法，参数传入我们定义的类RecyclerItemClickListener的实例
            recyclerViewMfg.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerViewMfg) {
                /**
                 * 点击事件
                 *
                 * @param viewHolder
                 */
                @Override
                public void onItemClick(RecyclerView.ViewHolder viewHolder, String sTag) {
                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    String sShortcutTag = sTag;
                    Log.e(TAG, "点击了快捷方式图标：" + sShortcutName);
                    //首页-快捷方式
                    openShortcutActivity(sShortcutTag);
                }

                /**
                 * 长按事件
                 *
                 * @param viewHolder
                 */

                @Override
                public void onLongClick(RecyclerView.ViewHolder viewHolder, String sTag) {

                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    Log.e(TAG, "长按了快捷方式图标：" + sShortcutName);
                }
            });

            recyclerViewMfg.setAdapter(mRecyclerViewMfgAdapter);

        }

        //endregion
    }

    //初始化数据-PE
    private void initFragmentPeFunctionView() {
        recyclerViewPe = viewFunction.findViewById(R.id.rvPe);  //显示-快捷图标(PE)
        vPe = viewFunction.findViewById(R.id.vPe);  //页签
        llPe = viewFunction.findViewById(R.id.llPe);
        llPe.setOnClickListener(v -> {
            if (recyclerViewPe.getVisibility() == View.GONE){
                recyclerViewPe.setVisibility(View.VISIBLE);
                vPe.setBackground(getResources().getDrawable(R.drawable.shape_view_red));
            }else {
                recyclerViewPe.setVisibility(View.GONE);
                vPe.setBackground(getResources().getDrawable(R.drawable.shape_view_white));
            }
        });
        if (mBasShortcutIconInfoPeList == null) {
            mBasShortcutIconInfoPeList = new ArrayList<>();
        }

        //region 获取pe本地Json数据(快捷图标)

        try {
            //获取本地Json数据(快捷图标)
            ResultSet resultSetData = FileUtils.readJson(mContext, "pe.txt");
            if (resultSetData.status == 0) {
                String sShortcutJson = resultSetData.getData().toString();
                if (!TextUtils.isEmpty(sShortcutJson)) {
                    //解析JSON
                    JSONArray jsonArray = new JSONArray(sShortcutJson);
                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                    String sData = jsonObject.getString("data");
                    JSONArray jsonArrayData = new JSONArray(sData);
                    JSONObject jsonObjectData = jsonArrayData.getJSONObject(0);
                    PDALoginReturnEntity mPDALoginReturnEntity = GsonUtils.getObject(jsonObjectData.toString(), PDALoginReturnEntity.class);
                    mBasShortcutIconInfoPeList.addAll(mPDALoginReturnEntity.getTabIndexGridEntityList());

                } else {
                    ToastUtil.showShortToast(mContext, resultSetData.msg);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

//endregion

//region 初始化数据

        if (mBasShortcutIconInfoPeList.size() >= 1) {

            //设置网格布局管理器
            recyclerViewPe.setLayoutManager(new GridLayoutManager(mContext, 3));
            // 设置adapter
            //快捷方式适配器(pe)
            RecyclerViewAdapter mRecyclerViewPeAdapter = new RecyclerViewAdapter(mContext, R.layout.item_main_operate, mBasShortcutIconInfoPeList);

            //分割线
            //recyclerViewPe.addItemDecoration(new DividerGridItemDecoration(this));
            recyclerViewPe.setHasFixedSize(true);

            // recyclerViewPe  调用自己的addOnItemTouchListener方法，参数传入我们定义的类RecyclerItemClickListener的实例
            recyclerViewPe.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerViewPe) {
                /**
                 * 点击事件
                 *
                 * @param viewHolder
                 */
                @Override
                public void onItemClick(RecyclerView.ViewHolder viewHolder, String sTag) {
                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    String sShortcutTag = sTag;
                    Log.e(TAG, "点击了快捷方式图标：" + sShortcutName);
                    //首页-快捷方式
                    openShortcutActivity(sShortcutTag);
                }

                /**
                 * 长按事件
                 *
                 * @param viewHolder
                 */

                @Override
                public void onLongClick(RecyclerView.ViewHolder viewHolder, String sTag) {

                    RecyclerViewAdapter.ViewHolder viewHolder1 = (RecyclerViewAdapter.ViewHolder) viewHolder;
                    String sShortcutName = viewHolder1.mTextView.getText().toString();
                    Log.e(TAG, "长按了快捷方式图标：" + sShortcutName);
                }
            });

            recyclerViewPe.setAdapter(mRecyclerViewPeAdapter);

        }

        //endregion
    }

//endregion

    //region 首页-快捷方式、功能 点击跳转

    //首页-快捷方式
    private void openShortcutActivity(String sShortcutTag) {
        if(sShortcutTag.equals("BatchStartWorkActivity")){
            FreeApi_Utils.skipWithExtraIntent("header", mContext, BatchStartWorkActivity.class);
            return;
        }

        if (sShortcutTag.equals("BatchEndWorkActivity")){
            FreeApi_Utils.skipWithExtraIntent("header", mContext, BatchEndWorkActivity.class);
            return;
        }


        Intent intent = new Intent(mContext, DialogActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        switch (sShortcutTag) {

            //批次开始操作
            case "BatchWorkBeginActivity":

                //region 批次开始操作
                intent.putExtra("showPlugin", "BatchWorkBeginActivity");
                break;

            //endregion

            //批次结束操作
            case "BatchWorkEndActivity":

                //region 批次结束操作
                intent.putExtra("showPlugin", "BatchWorkEndActivity");

                break;

            //endregion

            //材料更换
            case "MaterialExchangeActivity":

                //region 材料更换
                intent.putExtra("showPlugin", "MaterialExchangeActivity");

                break;

            //endregion

            //交接班检产量汇报
            case "ChangeShiftActivity":

                //region 交接班检产量汇报
                intent.putExtra("showPlugin", "ChangeShiftActivity");

                break;

            //endregion

            // Recipe下载
            case "RecipeDownLoadActivity":

                //region Recipe下载
                intent.putExtra("showPlugin", "RecipeDownLoadActivity");

                break;

            //endregion

            // Recipe上传
            case "RecipeUpLoadActivity":

                //region Recipe上传
                intent.putExtra("showPlugin", "RecipeUpLoadActivity");

                break;

            //endregion

            //工程模式
            case "EngineerModelActivity":
                //region 解锁

                intent.putExtra("showPlugin", "EngineerModelActivity");
                //endregion
                break;

        }
        startActivity(intent);

    }

//endregion

    //region 页面滑动-控件事件、切换功能、适配器

    //页面滑动-控件事件
    private void setListenerView() {
        //页面滑动-切换功能
        mViewPager.addOnPageChangeListener(mPageChangeListener);

        //点击-切换功能
//        rg_bottom_radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                for (int i = 0; i < group.getChildCount(); i++) {
//                    if (group.getChildAt(i).getId() == checkedId) {
//                        mViewPager.setCurrentItem(i);
//                        return;
//                    }
//                }
//            }
//        });
    }

    //页面滑动-切换功能
    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {

        /**
         * 当页面在滑动的时候会调用此方法，在滑动被停止之前，此方法回一直得到调用
         *
         * @param position 当前页面，及你点击滑动的页面
         * @param positionOffset 当前页面偏移的百分比
         * @param positionOffsetPixels 当前页面偏移的像素位置
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        /**此方法是页面跳转完后得到调用
         *
         * @param position 当前选中的页面的Position（位置编号）
         */
        @Override
        public void onPageSelected(int position) {
//            RadioButton radioButton = (RadioButton) rg_bottom_radio_group.getChildAt(position);
//            radioButton.setChecked(true);
        }

        /**
         * 此方法是在状态改变的时候调用
         *
         * @param state 此参数有三种状态（0，1，2）：state ==1的时辰默示正在滑动，state==2的时辰默示滑动完毕了，state==0的时辰默示什么都没做
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    //首页底部菜单-适配器
    private class FunPagerAdapter extends PagerAdapter {

        private List<View> mList;

        public FunPagerAdapter(List mList) {
            this.mList = mList;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView(mList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((ViewPager) container).addView(mList.get(position));
            return mList.get(position);
        }
    }

//endregion

}